package struts;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import struts.action.Action;
import struts.common.FullForm;
import struts.common.XmlBean;
import struts.form.ActionForm;

public class ActionServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7127150859111716940L;

	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		//获得请求头
		String path = this.getPath(request.getServletPath());
		Map<String,XmlBean> map = (Map<String, XmlBean>) this.getServletContext().getAttribute("struts");
		XmlBean xml = map.get(path);		
		String formclass = xml.getFormClass();
		ActionForm form = FullForm.full(formclass, request);
		String actiontype = xml.getActionClass();
		Action action = null;
		String url = "";
		System.out.println(form);
		try {
			@SuppressWarnings("rawtypes")
			Class clazz = Class.forName(actiontype);
			action = (Action) clazz.newInstance();
			url = action.execute(request, null, form, xml.getActionForward());
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("严重:控制器异常! ");
		}
		RequestDispatcher dis = request.getRequestDispatcher(url);
		dis.forward(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}
	private String getPath(String servletpath){
		return servletpath.split("\\.")[0];
	}
}
